/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * BasePermissionManageController
 * 基础权限管理
 * 修改纪录
 * 2020-10-26 版本：1.0 maxiaodong 创建。
 *
 * @version 版本：1.0
 * @author 作者：maxiaodong
 * 创建日期：2020-10-26
 */
package com.topscomm.base.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.topscomm.base.BaseSystemConst;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.meet.pojo.MeetManageEntity;
import com.topscomm.meet.service.IMeetManageService;
import com.topscomm.tap.common.SessionUserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.topscomm.base.BaseSystemConst.ShareTypeEnum;
import com.topscomm.base.controller.auto.BasePermissionManageControllerAuto;
import com.topscomm.base.pojo.BasePermissionManageEntity;
import com.topscomm.base.pojo.BaseTeamUserEntity;
import com.topscomm.base.service.IBasePermissionManageService;
import com.topscomm.base.service.IBaseTeamUserService;
import com.topscomm.base.service.impl.BaseCboUserExtendService;
import com.topscomm.base.service.impl.BaseShareManageService;
import com.topscomm.base.service.impl.BaseTeamInfoService;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.pojo.CboUserRoleEntity;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboUserRoleService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.work.pojo.WorkScheduleEntity;
import com.topscomm.work.service.IWorkScheduleService;
import springfox.documentation.spring.web.json.Json;

import static com.topscomm.security.utils.SecurityContextHolderWrapper.getSessionUserBean;

/**
 * @author: maxiaodong
 * @date: 2020-10-26
 * @description:基础权限管理Controller
 * @modify:
 */
@RestController
@RequestMapping("base/permissionManage")
public class BasePermissionManageController extends BasePermissionManageControllerAuto
		implements IBasePermissionManageController {
	@Autowired
	BaseCboUserExtendService baseCboUserExtendService;
	@Autowired
	BaseTeamInfoService baseTeamInfoService;
	@Autowired
	private ICboUserService cboUserService;
	@Autowired
	private IBasePermissionManageService basePermissionManageService;
	@Autowired
	private ICboDeptService cboDeptService;
	@Autowired
	private IBaseTeamUserService baseTeamUserService;
	@Autowired
	private ICboUserRoleService cboUserRoleService;
	@Autowired
	private IWorkScheduleService workScheduleService;
	@Autowired
	private IMeetManageService meetManageService;

	/**
	 * @author: maxiaodong
	 * @date: 2020-10-26
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_sharetype")) {
			String value = paraMap.get("qry_sharetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sharetype like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_shareobjectsdesc")) {
			String value = paraMap.get("qry_shareobjectsdesc").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and shareobjectsdesc = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourcetype")) {
			String value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourcetype = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourceid")) {
			String value = paraMap.get("qry_sourceid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceid = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourceflag")) {
			String value = paraMap.get("qry_sourceflag").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceflag = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_self")) {
			sql.appendSingle(" and sourceusercodes = '{0}' ", this.getUserBean().getUser().getCode());
		}
		return sql.toString();
	}

	/**
	 * @author: maxiaodong
	 * @date: 2020-10-26
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 * @description:查询已有人员
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月3日上午9:48:36
	 * @modify:
	 */
	@GetMapping(value = "/queryList")
	public ResponseResult<Object> queryList(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			List<BasePermissionManageEntity> list = this.service.queryByWhere(sqlWhere);
			return ResponseResult.ok(list);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/**
	 * @description:判断用户是否能够查看会议议程
	 * @param paraMap
	 * @return
	 * @author: chengengwei
	 * @date: 2021-2-19
	 * @modify:
	 */
	@GetMapping(value = "/judgeIsAttendUser")
	public ResponseResult<Object> judgeIsAttendUser(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			List<BasePermissionManageEntity> list = this.service.queryByWhere(sqlWhere);
			MeetManageEntity meetManageEntity = this.meetManageService.queryById(ConvertUtil
					.convertToString(paraMap.get("qry_sourceid")));
			// 会议秘书code
			String manageusercodes = "";
			List<String> manageusercodesList = new ArrayList<>();
			if (meetManageEntity.getManageusercodes() != null) {
				manageusercodes = meetManageEntity.getManageusercodes();
				manageusercodesList = Arrays.asList(manageusercodes.split(","));
			}
			// 判断当前用户是否是参会人员或会议秘书或发起人
			Map<String, Object> allUserMap = processToMapUsers(list);
			List<Map<String, Object>> allUserList = service.getAllAttendUser(allUserMap);
			SessionUserBean userBean = getSessionUserBean();
			String usercode = userBean.getUser().getCode();
			boolean isAttendUser = allUserList.stream().anyMatch(map -> usercode.equals(map.get("code")))
					|| manageusercodesList.contains(usercode) || meetManageEntity.getUsercode().equals(usercode);
			Map<String, Object> resultMap = new HashMap<>();
			resultMap.put("isAttendUser", isAttendUser);
			return ResponseResult.ok(resultMap);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/**
	 * @description:将BasePermissionManage表的list转前台Map格式
	 * @param list
	 * @return
	 * @author: chengengwei
	 * @date: 2021-2-19
	 * @modify:
	 */
	private Map<String, Object> processToMapUsers(List<BasePermissionManageEntity> list) {
		Map<String, Object> result = new HashMap<>();
		for (BasePermissionManageEntity basePermissionManageEntity : list) {
			if (BaseSystemConst.ShareTypeEnum.Dept.equals(basePermissionManageEntity.getSharetype())) {
				if (result.containsKey("deptcodes")) {
					result.put("deptcodes", result.get("deptcodes") + "," + basePermissionManageEntity.getShareobjects());
				} else {
					result.put("deptcodes", basePermissionManageEntity.getShareobjects());
				}
			} else if (BaseSystemConst.ShareTypeEnum.User.equals(basePermissionManageEntity.getSharetype())) {
				if (result.containsKey("usercodes")) {
					result.put("usercodes", result.get("usercodes") + "," + basePermissionManageEntity.getShareobjects());
				} else {
					result.put("usercodes", basePermissionManageEntity.getShareobjects());
				}
			} else if (BaseSystemConst.ShareTypeEnum.Role.equals(basePermissionManageEntity.getSharetype())) {
				if (result.containsKey("roleids")) {
					result.put("roleids", result.get("roleids") + "," + basePermissionManageEntity.getShareobjects());
				} else {
					result.put("roleids", basePermissionManageEntity.getShareobjects());
				}
			} else if (BaseSystemConst.ShareTypeEnum.Team.equals(basePermissionManageEntity.getSharetype())) {
				if (result.containsKey("teamids")) {
					result.put("teamids", result.get("teamids") + "," + basePermissionManageEntity.getShareobjects());
				} else {
					result.put("teamids", basePermissionManageEntity.getShareobjects());
				}
			} else if (BaseSystemConst.ShareTypeEnum.Share.equals(basePermissionManageEntity.getSharetype())) {
				if (result.containsKey("sharecodes")) {
					result.put("sharecodes", result.get("sharecodes") + "," + basePermissionManageEntity.getShareobjects());
				} else {
					result.put("sharecodes", basePermissionManageEntity.getShareobjects());
				}
			}
		}
		Set<String> tempSet = new HashSet<>();
		// 去重
		result.forEach((k, v) -> {
			String[] codes = ((String) v).split(",");
			tempSet.addAll(Arrays.asList(codes));
			result.put(k, tempSet.stream().collect(Collectors.joining(",")));
			tempSet.clear();
		});
		return result;
	}

	/**
	 * @description:查询所在二级部门人员
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月9日上午9:25:36
	 * @modify:
	 */
	@GetMapping(value = "querySelfDeptUser")
	public ResponseResult<Object> querySelfDeptUser(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String deptCode = this.getUserBean().getDept().getCode();
			try {
				int endIndex = 2, len = deptCode.length();
				if (deptCode.trim().indexOf("_") > -1) {
					endIndex = deptCode.trim().indexOf("_") + 3;
				}
				for (int i = 1; i <= 2; i++) {
					if (endIndex + 2 > len) {
						break;
					}
					endIndex += 2;
				}
				deptCode = deptCode.substring(0, endIndex);
			} finally {
			}
			StringBufferProxy sqlBufferProxy = new StringBufferProxy();
			sqlBufferProxy.appendLineSingle(
					"deptid in (select id from cbodept where code like '{0}%') and dimissiondate is null", deptCode);
			sqlBufferProxy.appendLineSingle("order by NLSSORT(name,'NLS_SORT = SCHINESE_PINYIN_M')  asc");
			List<CboUserEntity> list = this.cboUserService.queryByWhere(sqlBufferProxy.toString());
			List<Map<String, Object>> resultList = new ArrayList<>();
			for (CboUserEntity entity : list) {
				Map<String, Object> map = new HashMap<>();
				map.put("name", entity.getName());
				map.put("code", entity.getCode());
				resultList.add(map);
			}
			return ResponseResult.ok(resultList);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/**
	 * @author: maxiaodong
	 * @date: 2020-10-26
	 * @param paraMap
	 * @return
	 * @description:查询直接上级姓名
	 * @modify:
	 */
	@GetMapping(value = "/loadhname")
	public ResponseResult<Object> loadHname(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String userID = ConvertUtil.convertToString(paraMap.get("headerids"));
			List<CboUserEntity> result = this.cboUserService.queryByIds(userID);
			HashMap<String, Object> dataMap = new HashMap<>();
			dataMap.put("headersname", result.get(0).getName());
			System.out.println(dataMap);
			afterLoad(dataMap);
			return ResponseResult.ok(dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * 通过共享类型查询用户
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2020年11月4日上午10:36:35
	 * @modify:
	 */
	@GetMapping(value = "/queryUserListByShareType")
	public ResponseResult<Object> queryUserListByShareType(
			@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Query query = new Query(paraMap);
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			List<String> userCodeList = new ArrayList<>();
			String qry_deptcodes = ConvertUtil.convertToString(paraMap.get("deptcodes"));
			String qry_roleids = ConvertUtil.convertToString(paraMap.get("roleids"));
			String qry_teamids = ConvertUtil.convertToString(paraMap.get("teamids"));
			String qry_usercodes = ConvertUtil.convertToString(paraMap.get("usercodes"));
			String qry_sharecodes = ConvertUtil.convertToString(paraMap.get("sharecodes"));
			String qry_codelist = ConvertUtil.convertToString(paraMap.get("qry_codelist"));
			// 通过qry_codelist查询已选择的汇报人，只在回显已选择汇报人时使用
			if (qry_codelist != null) {
				String[] codeArray = qry_codelist.split(",");
				for (String s : codeArray) {
					userCodeList.add(s);
				}
			}
			// 通过部门查询用户
			if (qry_deptcodes.length() > 0) {
				List<Map<String, Object>> userList = baseCboUserExtendService.searchUsersByDeptCodes(qry_deptcodes);
				for (Map<String, Object> map : userList) {
					userCodeList.add(ConvertUtil.convertToString(map.get("code")));
				}
			}
			// 通过角色查询用户
			if (qry_roleids.length() > 0) {
				List<Map<String, Object>> userList = baseCboUserExtendService.searchUserByRoleIds(qry_roleids);
				for (Map<String, Object> map : userList) {
					userCodeList.add(ConvertUtil.convertToString(map.get("code")));
				}
			}
			// 通过团队查询用户
			if (qry_teamids.length() > 0) {
				List<Map<String, Object>> userList = baseTeamInfoService.getTeamMembers(qry_teamids);
				for (Map<String, Object> map : userList) {
					userCodeList.add(ConvertUtil.convertToString(map.get("usercode")));
				}
			}
			// 选择用户本身
			if (qry_usercodes.length() > 0) {
				String[] users = qry_usercodes.split(",");
				for (String code : users) {
					userCodeList.add(code);
				}
			}
			// 按共享人
			if (qry_sharecodes.length() > 0) {
				String[] users = qry_sharecodes.split(",");
				for (String code : users) {
					userCodeList.add(code);
				}
			}
			String selectUserCodes = String.join(",", userCodeList);
			// 通過用戶code查詢用戶
			StringBufferProxy sqlTemp = new StringBufferProxy();
			if (selectUserCodes != null) {
				String[] userCodeArray = selectUserCodes.split(",");
				if (userCodeArray != null && userCodeArray.length > 0) {
					List<String> userlist = new ArrayList<String>();
					String userCodeString = "";
					for (int i = 0; i < userCodeArray.length; i = i + 1) {
						if (i != 0 && i % 1000 == 0) {
							userCodeString = userCodeString.substring(0, userCodeString.length() - 1);
							userlist.add(userCodeString);
							userCodeString = "'" + userCodeArray[i] + "'" + ",";
						} else {
							userCodeString += "'" + userCodeArray[i] + "'" + ",";
						}
					}
					if (!StringUtil.isEmpty(userCodeString)) {
						userCodeString = userCodeString.substring(0, userCodeString.length() - 1);
						userlist.add(userCodeString);
					}
					for (int i = 0; i < userlist.size(); i++) {
						if (i == 0) {
							sqlTemp.appendSingle(" code in ({0})", userlist.get(i));
						} else {
							sqlTemp.appendSingle(" or code in ({0})", userlist.get(i));
						}
					}
				}
			}
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle("1=1");
			if (!StringUtil.isEmpty(sqlTemp.toString())) {
				sql.appendSingle(" and ({0} )", sqlTemp.toString());
			}
			if (paraMap.containsKey("qry_code")) {
				String code = ConvertUtil.convertToString(paraMap.get("qry_code"));
				if (code != null) {
					sql.appendSingle(" and code like '%{0}%' ", code);
				}
			}
			if (paraMap.containsKey("qry_name")) {
				String name = ConvertUtil.convertToString(paraMap.get("qry_name"));
				if (name != null) {
					sql.appendSingle(" and name like '{0}%' ", name);
				}
			}
			int totalCount = cboUserService.getCount(sql.toString());
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = cboUserService.queryMapForPage(sql.toString(), query.getCurrentPage(), query.getPageSize(),
						query.getSidx(), query.getSord());
			} else
				tempList = cboUserService.queryMapByWhere(sql.toString());
			cboUserService.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * @description: 根据usercode获取被共享人列表
	 * @param paraMap
	 * @author: maxiaodong
	 * @date: 2020年11月5日上午8:54:10
	 * @modify:
	 */
	@GetMapping(value = "/querySharers")
	public ResponseResult<Object> querySharers(@RequestParam(required = false) Map<String, Object> paraMap) {
		String userCode = ConvertUtil.convertToString(paraMap.get("qry_usercode"));
		paraMap.put("qry_currentuser", this.getUserBean().getUser().getCode());
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		List<Long> roleidList = new ArrayList<Long>();
		List<String> teamidList = new ArrayList<String>();
		// deptCode查询
		String deptCode = "";
		CboUserEntity userEntity = cboUserService.queryObjectByWhere("code='" + userCode + "'");
		CboDeptEntity deptEntity = cboDeptService.queryById(String.valueOf(userEntity.getDeptid()));
		// 所有角色查询
		List<CboUserRoleEntity> roleList = cboUserRoleService
				.queryByWhere(CboUserRoleEntity.FieldUserid + "='" + userEntity.getId() + "'");
		deptCode = deptEntity.getCode();
		for (CboUserRoleEntity cboUserRoleEntity : roleList) {
			roleidList.add(cboUserRoleEntity.getRoleid());
		}
		// 获取查询sql语句
		String deptWhereString = BaseShareManageService
				.createWhereDeptCheckInclude(BasePermissionManageEntity.FieldShareobjects, deptCode, ",");
		paraMap.put("qry_deptWhere", deptWhereString);
		paraMap.put("qry_roleidList", roleidList);
		// 所有团队查询
		List<BaseTeamUserEntity> teamList = baseTeamUserService
				.queryByWhere(BaseTeamUserEntity.FieldUsercode + "='" + userCode + "'");
		for (BaseTeamUserEntity baseTeamUserEntity : teamList) {
			teamidList.add(baseTeamUserEntity.getTeamid());
		}
		paraMap.put("qry_teamidList", teamidList);
		// 开始查询被共享人
		result = this.basePermissionManageService.queryMap(paraMap, "querySharers");
		return ResponseResult.ok(result);
	}

	/**
	 * @description: 任务时间冲突检测
	 * @param paraMap
	 * @return
	 * @author: maxiaodong
	 * @date: 2020年11月9日下午2:49:25
	 * @modify:
	 */
	@GetMapping(value = "/checkTimeConflict")
	public ResponseResult<Object> checkTimeConflict(@RequestParam(required = false) Map<String, Object> paraMap) {
		// 将传递的数据全部转换为usercode
		Set<String> sharers = this.basePermissionManageService.findAllSharersByMap(paraMap);
		// 再schedule表中找到所有begintime与endtime有冲突的记录
		List<String> filedList = new ArrayList<String>();
		filedList.add(WorkScheduleEntity.FieldId);
		filedList.add(WorkScheduleEntity.FieldEndtime);
		filedList.add(WorkScheduleEntity.FieldBegintime);
		filedList.add(WorkScheduleEntity.FieldName);
		String begintime = SQLAdapter.toDateLong(DateUtil.dateToString(
				DateUtil.stringToDate(ConvertUtil.convertToString(paraMap.get("begintime"))), "yyyy-MM-dd HH:mm:ss"));
		String endtime = SQLAdapter.toDateLong(DateUtil.dateToString(
				DateUtil.stringToDate(ConvertUtil.convertToString(paraMap.get("endtime"))), "yyyy-MM-dd HH:mm:ss"));
		StringBufferProxy querybywhere = new StringBufferProxy();
		querybywhere.appendSingle("( endtime > {0} and begintime < {1})", begintime, endtime);
		if (paraMap.containsKey("id")) {
			String scheduleId = ConvertUtil.convertToString(paraMap.get("id"));
			querybywhere.appendSingle(" and id != {0}", scheduleId);
		}
		//排除当前查询日程或会议
		if (paraMap.containsKey("sourceid") && paraMap.containsKey("sourcetype")) {
			String sourceid = ConvertUtil.convertToString(paraMap.get("sourceid"));
			String sourcetype = ConvertUtil.convertToString(paraMap.get("sourcetype"));
			querybywhere.appendSingle(" and (sourceid != '{0}' or sourcetype != '{1}')", sourceid, sourcetype);
		}
		// 查询这段时间内所有日程
		List<Map<String, Object>> workScheduleMapList = this.workScheduleService
				.queryMapFieldsByWhere(querybywhere.toString(), filedList);
		//没有日程 意味着不会有冲突
		if (workScheduleMapList.isEmpty()) {
			return ResponseResult.ok(new ArrayList<>());
		}
		List<Map<String, Object>> resultReturn;
		//根据service方法进行冲突检测
		resultReturn = this.basePermissionManageService.checkConflict(sharers,workScheduleMapList);
		return ResponseResult.ok(resultReturn);
	}
	/**
	  *
	  * @author xinfushuo
	  * @param
	  * @throws
	  * @return
	  * @date 2023/2/13
	  * @modify
	  */
	@PostMapping(value = "/queryUserByCode")
	public ResponseResult<Object> queryUserByCode(@RequestBody Map<String,Object> paraMap){
		BaseUtil.decodeSecureMap(paraMap);
		if(!paraMap.containsKey("usercodes")||paraMap.get("usercodes")==null){
			throw new ServiceException("无效参数，请重试！");
		}
		JSONArray list = (JSONArray) paraMap.remove("usercodes");
		List<String> usercodes = list.toJavaList(String.class);
		if(usercodes.isEmpty()){
			throw new ServiceException("无效参数，请重试！");
		}
		paraMap.put("usercodes",usercodes);
		List<Map<String,Object>> usercodeMapList = this.service.queryMap(paraMap,"queryUsersByCode");
		return  ResponseResult.ok(usercodeMapList);
	}
}
